<template>
  <div class="app-container">
    <el-form
      ref="sendSMSdata"
      :rules="rules"
      :model="sendSMSdata"
      label-width="100px"
      v-if="$route.query.typeId == '1'"
    >
      <div>
        短信推送
      </div>

      <el-table
        v-loading="tableLoading"
        ref="SMSsingleTable"
        :data="SMStemplate"
        highlight-current-row
        @current-change="messageTemplatechange"
        style="width: 100%"
      >
        <el-table-column
          type="index"
          width="50"
        >
        </el-table-column>
        <el-table-column
          property="templateName"
          label="模版名称"
          width="120"
        >
        </el-table-column>
        <el-table-column
          property="text"
          label="短信内容"
        >
        </el-table-column>
        <el-table-column
          label="选择"
          width="50"
        >
          <template slot-scope="scope">
            <el-radio
              v-model="sendSMSdata.code"
              :label="scope.row.code"
            >&nbsp;</el-radio>
          </template>
        </el-table-column>
      </el-table>

      <el-form-item label="选择用户:">
        <el-radio-group
          v-model="chooseUser"
          @change="clearChooseUser()"
        >
          <el-radio :label="1">全部用户</el-radio>
          <el-radio :label="3">特定用户</el-radio>
        </el-radio-group>
      </el-form-item>

      <div
        class="choose_user_box"
        v-if="chooseUser == 3"
      >
        <el-form-item
          label="手机号:"
          prop="userPhone"
        >
          <el-input v-model="sendSMSdata.userPhone"></el-input>
        </el-form-item>
      </div>

      <el-form-item>
        <el-button
          type="primary"
          @click="doSendSMS('sendSMSdata')"
        >发送消息</el-button>
      </el-form-item>

    </el-form>

    <el-form
      ref="pushYouMengdata"
      :rules="rules"
      :model="pushYouMengdata"
      label-width="100px"
      v-if="$route.query.typeId == '2'"
    >
      <div>
        友盟推送
      </div>

      <el-table
        v-loading="tableLoading"
        ref="youMengsingleTable"
        :data="YouMengTemplate"
        highlight-current-row
        @current-change="youMengTemplatechange"
        style="width: 100%"
      >
        <el-table-column
          type="index"
          width="50"
        >
        </el-table-column>
        <el-table-column
          property="ticker"
          label="模版名称"
          width="120"
        >
        </el-table-column>
        <el-table-column
          property="typeName"
          label="推送类型"
          width="120"
        >
        </el-table-column>
        <el-table-column
          property="title"
          label="推送标题"
          width="120"
        >
        </el-table-column>
        <el-table-column
          property="templateContext"
          label="站外推送内容"
        >
        </el-table-column>
        <el-table-column
          label="选择"
          width="50"
        >
          <template slot-scope="scope">
            <el-radio
              v-model="pushYouMengdata.id"
              :label="scope.row.id"
            >&nbsp;</el-radio>
          </template>
        </el-table-column>
      </el-table>

      <el-form-item label="选择用户:">
        <el-radio-group
          v-model="chooseYouMengUser"
          @change="clearChooseUser()"
        >
          <el-radio :label="1">全部用户</el-radio>
          <el-radio :label="3">特定用户</el-radio>
        </el-radio-group>
      </el-form-item>

      <div
        class="choose_user_box"
        v-if="chooseYouMengUser == 3"
      >
        <el-form-item
          label="用户ID:"
          prop="userId"
        >
          <el-input v-model="pushYouMengdata.userId"></el-input>
        </el-form-item>
      </div>

      <el-form-item>
        <el-button
          type="primary"
          @click="doYouMengPush('pushYouMengdata')"
        >发送消息</el-button>
      </el-form-item>

    </el-form>

    <el-form
      ref="pushAPPdata"
      :rules="rules"
      :model="pushAPPdata"
      label-width="100px"
      v-if="$route.query.typeId =='3'"
    >
      <div>
        站内推送
      </div>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item
            label="推送类型"
            prop="typeIdOptionsValue"
          >
            <el-select
              v-model="typeIdOptionsValue"
              placeholder="请选择"
            >
              <el-option
                v-for="item in typeIdOptions"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="标题"
            prop="titleName"
          >
            <el-input v-model="pushAPPdata.titleName"></el-input>
          </el-form-item>
          <el-form-item
            label="内容"
            prop="msgContent"
          >
            <el-input
              type="textarea"
              v-model="pushAPPdata.msgContent"
            ></el-input>
          </el-form-item>
          <el-form-item label="链接">
            <el-input v-model="pushAPPdata.link"></el-input>
          </el-form-item>

          <el-form-item label="选择用户:">
            <el-radio-group
              v-model="chooseAPPUser"
              @change="clearChooseUser()"
            >
              <el-radio :label="1">全部用户</el-radio>
              <el-radio :label="3">特定用户</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="用户ID"
            prop="sendUsers"
            v-if="chooseAPPUser =='3'"
          >
            <el-input v-model="pushAPPdata.sendUsers"></el-input>
          </el-form-item>

          <el-form-item label="">
            <div class="upload">
              <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :on-remove="handleRemove"
                :file-list="fileList2"
                name="files"
                :on-success="handleAvatarSuccess"
                list-type="picture"
              >
                <el-button
                  size="small"
                  type="primary"
                >选择图片</el-button>
                <!-- <div
                  slot="tip"
                  class="el-upload__tip"
                >只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="doAPPPush('pushAPPdata')"
            >发送消息</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">

        </el-col>
      </el-row>

    </el-form>

  </div>
</template>
<script>
import {
  fetchSendSMS,
  fetchGetSMSTemplate,
  fetchYouMengTemplateData,
  fetchYouMengPushData,
  fetchMessageTypeData,
  fetchAppMessagePushData,
  fetchUploadImg
} from "@/api/other";
export default {
  data() {
    return {
      sendSMSdata: {
        code: "",
        text: "",
        userPhone: ""
      },
      pushYouMengdata: {
        id: "",
        text: "",
        userId: "",
        typeName: ""
      },
      pushAPPdata: {
        titleName: "",
        msgContent: "",
        img: "",
        link: "",
        sendUsers: ""
      },
      physiologicalDataId: "",
      chooseUser: 1,
      chooseYouMengUser: 1,
      chooseAPPUser: 1,
      rules: {
        titleName: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        msgContent: [
          { required: true, message: "内容不能为空", trigger: "blur" },
          { min: 5, max: 1500, message: "长度在5到1500个字符", trigger: "blur" }
        ],
        userPhone: [
          {
            required: true,
            message: "手机号不能为空",
            trigger: "blur"
          },
          {
            min: 11,
            max: 11,
            message: "请输入正确的手机号",
            trigger: "blur"
          }
        ],
        noText: [{ required: true, message: "不能为空", trigger: "blur" }],
        name: [
          { required: true, message: "模版名称不能为空", trigger: "blur" },
          {
            max: 20,
            message: "请输入小于20个字内的名称",
            trigger: "blur"
          }
        ],
        code: [{ required: true, message: "CODE不能为空", trigger: "blur" }],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        sendUsers: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ]
      },
      SMStemplate: [],
      YouMengTemplate: [],
      checked: true,
      SMScurrentRow: null,
      youMengcurrentRow: null,
      typeIdOptions: [],
      typeIdOptionsValue: 2,
      tableLoading: false,
      //选择模板
      templateRadio: "",
      //上传图片
      fileList2: [],
      //获取到服务器上图片
      imgListData: [],
      //上传链接
      uploadUrl: ""
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      //上传图片链接
      this.uploadUrl = process.env.BASE_API + "/picture/upload";
      if (this.$route.query.typeId == "1") {
        this.getSMStemplate();
      } else if (this.$route.query.typeId == "2") {
        this.getYouMengTemplateData();
      } else if (this.$route.query.typeId == "3") {
        this.getMessageTypeData();
      }
    },
    handleRemove(file, fileList) {
      this.imgListData = "";
    },
    handleAvatarSuccess(res, file) {
      this.imgListData = res.data;
    },
    clearChooseUser() {
      this.sendSMSdata.userPhone = "";
      this.pushYouMengdata.userId = "";
      this.pushAPPdata.sendUsers = "";
    },
    setMessageTemplateCurrent(row) {
      this.$refs.SMSsingleTable.setCurrentRow(row);
    },
    setYouMengTemplateCurrent(row) {
      this.$refs.youMengsingleTable.setCurrentRow(row);
    },
    messageTemplatechange(val) {
      this.sendSMSdata.code = val.code;
    },
    youMengTemplatechange(val) {
      this.pushYouMengdata.id = val.id;
    },
    doSendSMS(sendSMS) {
      this.$refs[sendSMS].validate(valid => {
        if (this.sendSMSdata.code == "") {
          this.$message({
            type: "error",
            message: "请选择短信模版"
          });
          return;
        }
        if (valid) {
          let sendConfirmText = "";
          if (this.chooseUser !== 3) {
            sendConfirmText = "是否发送给全部用户";
          } else {
            sendConfirmText =
              "是否发送给" + this.sendSMSdata.userPhone + "用户";
          }
          this.$confirm(sendConfirmText, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.sendSMSData();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消"
              });
            });
        }
      });
    },
    async getSMStemplate() {
      this.tableLoading = true;
      const res = await fetchGetSMSTemplate();
      if (res.status == "200") {
        this.tableLoading = false;
        this.SMStemplate = [];
        res.data.forEach(item => {
          const template = {};
          template.code = item.templateCode;
          template.text = item.templateContext;
          template.templateName = item.templateName;
          this.SMStemplate.push(template);
        });
        this.setMessageTemplateCurrent(this.SMStemplate[0]);
      }
    },
    async sendSMSData() {
      if (this.checked) {
        this.checked = false;
        const res = await fetchSendSMS({
          physiologicalDataId: this.physiologicalDataId,
          recNum: this.sendSMSdata.userPhone,
          templateCode: this.sendSMSdata.code,
          chooseUser: this.chooseUser
        });
        this.checked = true;
        if (res.status == "200") {
          this.$message({
            type: "success",
            message: res.msg
          });
        } else {
          this.$message({
            type: "error",
            message: res.msg
          });
        }
      }
    },

    doYouMengPush(pushYouMeng) {
      this.$refs[pushYouMeng].validate(valid => {
        if (this.pushYouMengdata.id == "") {
          this.$message({
            type: "error",
            message: "请选择短信模版"
          });
          return;
        }
        if (valid) {
          let sendConfirmText = "";
          if (this.chooseYouMengUser !== 3) {
            sendConfirmText = "是否发送给全部用户";
          } else {
            sendConfirmText =
              "是否发送给" + this.sendSMSdata.userPhone + "用户";
          }
          this.$confirm(sendConfirmText, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.pushYouMeng();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消"
              });
            });
        }
      });
    },
    async getYouMengTemplateData() {
      this.tableLoading = true;
      const templateData = await fetchYouMengTemplateData();
      if (templateData.status == "200") {
        this.tableLoading = false;
        this.YouMengTemplate = [];
        templateData.data.forEach(item => {
          const template = {};
          template.id = item.id;
          template.title = item.title;
          template.ticker = item.ticker;
          template.templateContext = item.templateContext;
          template.typeName = item.typeName;
          this.YouMengTemplate.push(template);
        });
        this.setYouMengTemplateCurrent(this.YouMengTemplate[0]);
      }
    },
    async pushYouMeng() {
      const youMengPush = await fetchYouMengPushData({
        userId: this.pushYouMengdata.userId,
        pushMessageTemplateId: this.pushYouMengdata.id,
        chooseUser: this.chooseYouMengUser
      });
      if (youMengPush.status == "200") {
        this.$message({
          type: "success",
          message: "推送成功"
        });
      } else {
        this.$message({
          type: "error",
          message: youMengPush.msg
        });
      }
    },
    doAPPPush(pushAPP) {
      this.$refs[pushAPP].validate(valid => {
        if (valid) {
          let sendConfirmText = "";
          if (this.chooseAPPUser !== 3) {
            sendConfirmText = "是否发送给全部用户";
          } else {
            sendConfirmText =
              "是否发送给" + this.pushAPPdata.sendUsers + "用户";
          }
          this.$confirm(sendConfirmText, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.appMessagePush();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消"
              });
            });
        }
      });
    },
    async appMessagePush() {
      const appMessage = await fetchAppMessagePushData({
        sendUsers: this.pushAPPdata.sendUsers,
        typeId: this.typeIdOptionsValue,
        chooseUser: this.chooseAPPUser,
        title: this.pushAPPdata.titleName,
        content: this.pushAPPdata.msgContent,
        img: this.imgListData[0],
        link: this.pushAPPdata.link
      });
      this.$message({
        type: "success",
        message: "推送成功"
      });
    },
    async getMessageTypeData() {
      const typeList = await fetchMessageTypeData();
      this.typeIdOptions = [];
      if (typeList.data) {
        typeList.data.forEach(item => {
          if (item.id !== 1 && item.id !== 4) {
            const typedata = {};
            typedata.id = item.id;
            typedata.typeName = item.typeName;
            this.typeIdOptions.push(typedata);
          }
        });
      }
    }
  },
  watch: {
    "$route.query.typeId": function() {
      this.initData();
    }
  }
};
</script>
<style lang="less" scoped>
.message_template {
  text-align: center;
  color: #999;
}
.message_template_top {
  font-size: 16px;
  color: #000;
}
.border_top {
  border-top: 1px solid #000;
}
</style>

